package cn.zcf.org.service.impl;

import cn.zcf.basic.service.impl.BaseServiceImpl;
import cn.zcf.basic.utils.PageList;
import cn.zcf.org.domain.Dept;
import cn.zcf.org.mapper.DeptMapper;
import cn.zcf.org.query.DeptQuery;
import cn.zcf.org.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Service
public class DeptServiceImpl extends BaseServiceImpl<Dept> implements IDeptService {
    @Autowired
    private DeptMapper mapper;

    @Override
    public void add(Dept dept) {

        mapper.add(dept);
        update(dept);
    }

    @Override
    public void update(Dept dept) {

        if(dept.getParent_id()==null){
            Long id = dept.getId();
            //  设置dirPath
            dept.setDirPath("/"+id);
        }else{   // 2. 有上级部门
            // 通过parent_id 获取上级的dirPath
            Long parent_id = dept.getParent_id();
            // 父级部门对象
            Dept parentDept = mapper.loadById(parent_id);
            // dirPath
            dept.setDirPath(parentDept.getDirPath()+"/"+dept.getId());
        }

        mapper.update(dept);
    }


    @Override
    public List<Dept> deptTree() {
        List<Dept> all = mapper.loadAll();
        HashMap<Long, Dept> map = new HashMap<>();
        for (Dept dept : all) {
            map.put(dept.getId(),dept);
        }
        List<Dept> deptTree = new ArrayList<>();
        for (Dept dept : all) {
            if(dept.getParent_id()==null){
                deptTree.add(dept);
            }
            else {
                Dept parentDept = map.get(dept.getParent_id());
                parentDept.getChildren().add(dept);
            }
        }
        return deptTree;
    }
}
